import { isString } from "..";

/**
 * 保留定长，不足补零
 * @param {String | Number} num
 * @param {Number} len 要保留的长度
 * @returns {String}
 */
export const cut = (num: string | number, len: number) => {
  return num.toString().padStart(len, "0").slice(-len);
};

export const DATE_TIME_FORMAT = "YYYY-MM-DD HH:mm:ss";
export const DATE_FORMAT = "YYYY-MM-DD";
export const DATE_FORMAT_TM = "YYYY-MM-DD HH:mm";

/**
 * 格式化日期
 * @param {Date | String} date
 * @param {String} format
 */
export const dateFormat = (
  date: Date | string = new Date(),
  format = DATE_TIME_FORMAT
) => {
  if (isString(date) || Number.isInteger(date)) date = new Date(date);

  const Y = date.getFullYear();
  const M = date.getMonth() + 1;
  const D = date.getDate();
  const H = date.getHours();
  const h = H % 12;
  const m = date.getMinutes();
  const s = date.getSeconds();

  return format
    .replace(/Y{4,}/g, cut(Y, 4))
    .replace(/Y{3}/g, cut(Y, 3))
    .replace(/Y{2}/g, cut(Y, 2))
    .replace(/Y/g, cut(Y, 4))
    .replace(/M{2,}/g, cut(M, 2))
    .replace(/M/g, M.toString())
    .replace(/D{2,}/g, cut(D, 2))
    .replace(/D/g, D.toString())
    .replace(/H{2,}/g, cut(H, 2))
    .replace(/H/g, H.toString())
    .replace(/h{2,}/g, cut(h, 2))
    .replace(/h/g, h.toString())
    .replace(/m{2,}/g, cut(m, 2))
    .replace(/m/g, m.toString())
    .replace(/s{2,}/g, cut(s, 2))
    .replace(/s/g, s.toString());
};

/**
 * 比较日期大小
 */
export const dateCompare = (date1: Date | string, date2: Date | string) => {
  if (isString(date1)) date1 = new Date(date1);
  if (isString(date2)) date2 = new Date(date2);

  return +date1 - +date2;
};
